(function (window) {
    'use strict';
    var Event = function (element, type) {
        this.element = element;
        this.type = type;
    };
    Event.prototype = {
        add: function (callback) {
            this.callback = callback;
            this.element.addEventListener(this.type, this.callback, false);
        },
        remove: function () {
            this.element.removeEventListener(this.type, this.callback, false);
        }
    };
    var TransitionEnd = function (element) {
        this.element = element;
        this.transitionEnd = this.whichTransitionEnd();
        this.event = new Event(this.element, this.transitionEnd);
    };
    TransitionEnd.prototype = {
        whichTransitionEnd: function () {
            var transitions = {
                'WebkitTransition': 'webkitTransitionEnd',
                'MozTransition': 'transitionend',
                'OTransition': 'oTransitionEnd otransitionend',
                'transition': 'transitionend'
            };
            for (var t in transitions) {
                if (this.element.style[t] !== undefined) {
                    return transitions[t];
                }
            }
        },
        bind: function (callback) {
            this.event.add(callback);
        },
        unbind: function () {
            this.event.remove();
        }
    };
    var Cache = {
        list: [],
        getPosition: function (element) {
            if (Array.prototype.indexOf) {
                return this.list.indexOf(element);
            }
            for (var i = 0, size = this.list.length; i < size; i++) {
                if (this.list[i] === element) {
                    return i;
                }
            }
            return -1;
        },
        insert: function (element) {
            var positonElement = this.getPosition(element);
            var isCached = positonElement !== -1;
            if (!isCached) {
                this.list.push(element);
                this.list.push(new TransitionEnd(element));
                positonElement = this.getPosition(element);
            }
            return this.list[positonElement + 1];
        }
    };
    window.transitionEnd = function (el) {
        if (!el) {
            throw 'You need to pass an element as parameter!';
        }
        var element = el[0] || el;
        var instance = Cache.insert(element);
        return instance;
    };
}(window));

var shakeTreeObj = function (options) {
    var self = this;
    this.opt = $.extend({
        coreID: "#J_coin_a",
        testButton: "#J_test_btn",
        shakeID: "#J_shake",
        gameBox: "#J_gameTime"
    }, options, {});
    this.$_coina = $(self.opt.coreID);
//设置多个金币
    this.coins = [];
    this.$ca = $('<i class="coin-a coin"></i>');
    this.$yb = $('<i class="coin-yb coin"></i>');
    this.$cc = $('<i class="coin-ca coin"></i>');
    this.staticBeginTimer=3;
    this.staticGameTimer=10;
    this.staticShakeCount=0;
    this.beginTimer = this.staticBeginTimer;
    this.gameTimer = this.staticGameTimer;
    this.shakeCount = 0;
    this.$shakeText=$("#J_shakeCount");
    this.$becText=$("#J_times");
    this.$countParent=$("#J_countparent");
    this.$gameTime=$("#J_gametime");
    this.$gameResult=$("#J_result_shake");
    this.$optbar=$("#J_optbar");
    this.$revertBtn=$("#J_btn_revert");
    this._animover=true;
    this.$voice=$("#J_voice");
    this._voiceLoad=false;
    this._voiceText=$("#J_voice_click");
}
shakeTreeObj.prototype = {
    runCoin: function () {
        var self = this;
        var coinArr=[];
        self.$voice[0].volume=1.0;
        self.$voice[0].play();
    if($(".coin").size()<=20){
        for (var i = 0; i < 30; i++) {
            //设置多个对象
            coinArr[i] = Math.random() > 0.5 ? (Math.random() > 0.5 ? (this.$ca.clone()) : this.$cc.clone()) : this.$yb.clone();
            var randomDeg = Math.random() * 3600;
            if (randomDeg < 1080) {
                randomDeg = 1080
            }
            var randomLeft = Math.random(), scaleRandom = Math.random(), topRandom = Math.random();
            if (scaleRandom < 0.4) {
                scaleRandom += 0.4;
            }
            if (topRandom < 0.35) {
                topRandom = 0.35
            } else if (topRandom > 0.8) {
                topRandom = 0.8;
            }
            if (randomLeft < 0.2) {
                randomLeft = 0.2
            } else if (randomLeft > 0.7) {
                randomLeft = 0.7
            }
            self._animover=false;
            coinArr[i].css({
                "transform": "rotate(" + randomDeg + "deg) scale(" + scaleRandom + ")",
                "left": randomLeft * 100 + "%",
                "top": topRandom * 100 + "%",
                "opacity":0
            });
            coinArr[i].appendTo("body").off("one").one("mozTransitionend webkitTransitionEnd transitionend oTransitionEnd otransitionend", function () {
                $(this).remove();
            });
            var randomTime = Math.random() * 1000;
            if (randomTime < 200) {
                randomTime = 200
            };
            (function (i) {
                self.timer = window.setTimeout(function () {
                    coinArr[i].css({
                        "transform": "rotate(0deg) scale(1)",
                        "opacity": 1,
                        "top": "110%"
                    });
                    //清空数据
                }, randomTime);
            })(i);
        }
    }
       self.shakeCount++;
       this.$shakeText.html(self.shakeCount);
    },
    beginGame:function(){
        var self = this;
        self._interval=window.setInterval(function(){
            var timerText=self.beginTimer--;
            if(timerText==0){
                timerText="开始摇吧!";
                self.$becText.hide();
                self.$countParent.show();
                window.clearInterval(self._interval);
                self.startShake();
            }
            self.$becText.html(timerText);
        },1000);
    },
    restartGame:function(){
    	var self=this;
    	self.beginTimer = self.staticBeginTimer;
		self.gameTimer =  self.staticGameTimer;
		self.shakeCount = 0;
    	//检测摇奖次数是否有剩余
    	$.ajax({
			url : "/yao1/checkLottery",
			method : "GET",
			error : function() {
				Showbo.Msg.alert("error");
			},
			success : function(data) {
				if("false"==data){
					Showbo.Msg.alert("摇钱次数已用完，邀请好友参与可获得更多摇钱次数！");
					return false;
				}else{
				       //三大变量
				        self.$optbar.hide();
				        self.$countParent.hide();
				        self.$gameTime.html(self.gameTimer+"s").show();
				        self.$shakeText.html(0);
				        self.$gameResult.hide();
				        self.$becText.html("游戏开始,快摇吧！").show();
				        self._gamerOver=false;
				        self.beginGame();
				}
			}
				
		});
    },
    startShake:function(){
       var self = this;
       self._shakeInterval=window.setInterval(function(){
             self.gameTimer--;
             if(self.gameTimer==0){
                 self.gameTimer="时间到，游戏结束!";
                 self.$gameTime.html(self.gameTimer);
                self.gameOver();
             }else{
                 self.$gameTime.html(self.gameTimer+"s");
             }
       },1000);
    },

    gameOver:function(){
        var self = this;
        //clear timer;
         window.clearInterval(self._shakeInterval);
        $(".coin").remove();
        self._gamerOver=true;
        self.$gameTime.hide();
 		$.ajax({
			url : "/yao1/lottery?count="+this.shakeCount,
			method : "GET",
			dataType: 'json', 
			error : function() {
				Showbo.Msg.alert("error");
			},
			success : function(data) {
//				Showbo.Msg.alert(data);
//					var resultObj={
//			            isPrize:true,
//			            prize:"九方门票5张"
//			        }
			        self.$gameTime.hide();
//			        if(resultObj.isPrize){
//			            self.$gameResult.html("本次获得:"+resultObj.prize);
//			        }else{
			        self.$gameResult.html(data.prizeInfo);
//			        }
			        self.$optbar.fadeIn();
			        self.$gameResult.fadeIn();
			}
				
		});
        
        
    },
    oEvent: function () {
        var self = this;
        var $_testBtn = $(self.opt.testButton);
        /*测试代码*/
//        $(document).on("touchstart",function(e){
//            if(self.gameTimer>0&&!self._gamerOver){
//                self.runCoin();
//            }
//        });
        $_testBtn.on("click", function (e) {
            if(self.gameTimer>0&&!self._gamerOver){
                self.runCoin();
            }
            return false;
        });
        this._voiceText.on("touchstart",function(e){
        	var $_icon=$(this).find("i");
        	var $_text=$(this).find("span").html("音效已开启");
        	$_icon.removeClass("icon-shengyin1").addClass("icon-shengyin2");
        	self.$voice[0].play();
        	self.$voice[0].volume=0.0;
        	self.$voice[0].pause();
        });
        /*
        * -----------------------shake code-----------------------
        * */
        var SHAKE_THRESHOLD = 2000;
        var last_update = 0;
        var x = y = z = last_x = last_y = last_z = 0;
        function deviceMotionHandler(eventData) {
            var acceleration = eventData.accelerationIncludingGravity;
            var curTime = new Date().getTime();
            if ((curTime - last_update) > 100) {
                var diffTime = curTime - last_update;
                last_update = curTime;
                x = acceleration.x;
                y = acceleration.y;
                z = acceleration.z;
                var speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000;
                if (speed > SHAKE_THRESHOLD) {
                    //trigger shake
                    if(self.beginTimer<=0&&self.gameTimer>0&&!self._gamerOver){
                        self.runCoin();
                    }
                }
                last_x = x;
                last_y = y;
                last_z = z;
            }
        }
        if (window.DeviceMotionEvent) {
            window.addEventListener('devicemotion', deviceMotionHandler, false);
        } else {
            alert('not support mobile event');
        }
        /*-----------重新开始游戏----------*/
        this.$revertBtn.on("click",function(e){
            self.restartGame();
            return false;
        });
        //play
       $(document).on("touchstart",function(e){
        	self.$voice[0].play();
        	self.$voice[0].pause();
        	e.stopPropagation();
        });
    },
    init: function () {
        var self = this;
        self.beginGame();
        self.oEvent();
    }
};

$(function () {
    var sharkTree = new shakeTreeObj();
    sharkTree.init();
    var autumn=new Autumn();
    autumn.init();
    $("#J_friend_share").on("tap", function(e) {
        autumn.showMask(e);
        return false;
    });

});